package com.mtnz.njk.Util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class NewDateUtil {

    /**
     * @param nums         获取的天数
     * @param unit         ChronoUnit的类型
     * @param formatterStr 格式化格式类型
     * @return
     */
    public static String[] getDates(int nums, TemporalUnit unit, String formatterStr) {
        String[] str = new String[nums];
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatterStr);
        for (int i = 0; i < nums; i++) {
            LocalDateTime now = LocalDateTime.now();
            now = now.minus(i, unit);
            str[i] = formatter.format(now);
        }
        return str;
    }

    public static void main(String[] args) {
        String[] strs = NewDateUtil.getDates(7, ChronoUnit.DAYS, "yyyy-MM-dd");
        for (String str : strs) {
            System.out.println(str);
        }
    }

    public static List<String> getDays(String startTime, String endTime) { // 返回的日期集合
        List<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

}
